import { announcementApi, attendenceApi } from "../../utils/api"
import { getUserInfo } from "../../utils/auth"

// 考勤管理页面逻辑
Component({
  data: {
    // 星期标题
    weekDays: ['日', '一', '二', '三', '四', '五', '六'],
    
    // 当前月份
    currentMonth: '',
    
    // 日历数据
    calendarDays: [],
    
    // 公告列表
    notices: [
    ],
    
    // 模拟考勤数据
    attendanceData: {
      '2024-01-15': 'present',
      '2024-01-16': 'present', 
      '2024-01-17': 'leave',
      '2024-01-18': 'present',
      '2024-01-19': 'absent'
    }
  },

  methods: {
    // 页面加载时初始化
    onLoad() {
      this.initCalendar()
      this.initAnnouncement()
      this.initAttendanceRecord()
    },

    handlerGobackClick() {
      wx.navigateBack({
        delta: 1
      })
    },

    initAnnouncement() {
      // 请求公告列表接口
      announcementApi.getAnnouncementList().then(res => {
        this.setData({
          notices: res.data
        })
      })
    },

    initAttendanceRecord() {
      // 请求考勤记录接口
      attendenceApi.checkRecord({
        employeeId: getUserInfo().employeeId,
        checkMonth: `${this.data.currentMonth}`.replace('年', '-').replace('月', '')
      }).then(res => {
        this.setData({
          attendanceData: res.data
        })

          const currentMonth = `${this.data.currentMonth}`.replace('年', '-').replace('月', '').split('-');
          const year = parseInt(currentMonth[0], 10);
          const month = parseInt(currentMonth[1], 10);
          this.generateCalendar(year, month);
      })
    },

    // 初始化日历
    initCalendar() {
      const now = new Date()
      const year = now.getFullYear()
      const month = now.getMonth() + 1
      
      this.setData({
        currentMonth: `${year}年${month}月`
      })
      
      this.generateCalendar(year, month)
    },

    // 生成日历数据
    generateCalendar(year: number, month: number) {
      const firstDay = new Date(year, month - 1, 1)
      const lastDay = new Date(year, month, 0)
      const daysInMonth = lastDay.getDate()
      const firstDayOfWeek = firstDay.getDay() // 0-6 (日-六)
      
      const calendarDays = []
      const today = new Date()
      
      // 填充前面的空白
      for (let i = 0; i < firstDayOfWeek; i++) {
        calendarDays.push({ date: '', isEmpty: true })
      }
      
      // 生成当月日期
      for (let day = 1; day <= daysInMonth; day++) {
        const dateStr = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
        const isToday = today.getDate() === day && 
                       today.getMonth() + 1 === month && 
                       today.getFullYear() === year
        const isWeekend = new Date(year, month - 1, day).getDay() === 0 || 
                         new Date(year, month - 1, day).getDay() === 6
        
        calendarDays.push({
          date: day,
          dateStr: dateStr,
          isToday: isToday,
          isWeekend: isWeekend,
          status: this.data.attendanceData[dateStr] || null
        })
      }

      console.log('calendarDays:', calendarDays)
      
      this.setData({ calendarDays })
    },

    // 切换月份
    switchMonth(direction: number) {
      const currentDate = new Date()
      let year = currentDate.getFullYear()
      let month = currentDate.getMonth() + 1
      
      // 这里简单处理月份切换，实际应该基于当前显示的月份
      if (direction > 0) {
        month += 1
        if (month > 12) {
          month = 1
          year += 1
        }
      } else {
        month -= 1
        if (month < 1) {
          month = 12
          year -= 1
        }
      }
      
      this.setData({
        currentMonth: `${year}年${month}月`
      })
      
      this.generateCalendar(year, month)
    },

    // 查看考勤详情
    viewAttendanceDetail(e: any) {
      const index = e.currentTarget.dataset.index
      const day = this.data.calendarDays[index]
      
      if (day && !day.isEmpty) {
        wx.showModal({
          title: `${day.dateStr} 考勤详情`,
          content: this.getAttendanceStatusText(day.status),
          showCancel: false
        })
      }
    },

    // 获取考勤状态文本
    getAttendanceStatusText(status: string): string {
      switch (status) {
        case 'present':
          return '正常出勤'
        case 'leave':
          return '请假'
        case 'absent':
          return '缺勤'
        default:
          return '未记录'
      }
    },

    // 日期点击事件
    onDayTap(e: any) {
      const day = e.currentTarget.dataset.day
      
      // 只处理今天的日期且未签到的情况
      if (day.isToday && !day.status) {
        this.showCheckInConfirm(day)
      } else if (day.status) {
        // 如果已有考勤记录，显示详情
        this.viewAttendanceDetail(e)
      }
    },

    // 显示签到确认弹窗
    showCheckInConfirm(day: any) {
      wx.showModal({
        title: '签到确认',
        content: `确定要在 ${day.dateStr} 签到吗？`,
        success: (res) => {
          if (res.confirm) {
            this.handleCheckIn(day)
          }
        }
      })
    },

    // 处理签到
    async handleCheckIn(day: any) {
      try {
        wx.showLoading({ title: '签到中...' })
        
        // 获取用户信息
        const userInfo = getUserInfo()
        if (!userInfo) {
          wx.hideLoading()
          wx.showToast({ title: '请先登录', icon: 'error' })
          return
        }

        // 调用签到接口
        const result = await attendenceApi.checkIn({
          employeeId: userInfo.employeeId,
          checkDate: day.dateStr
        })

        wx.hideLoading()
        
        console.log('签到结果:', result)
        if (result.code === 200) {
          // 更新本地数据
          const attendanceData = { ...this.data.attendanceData }
          attendanceData[day.dateStr] = 'present'
          
          this.setData({
            attendanceData
          })
          
          // 重新生成日历以显示签到状态
          this.generateCalendar(new Date().getFullYear(), new Date().getMonth() + 1)
          
          wx.showToast({ 
            title: '签到成功', 
            icon: 'success',
            duration: 2000
          })
        } else {
          wx.showToast({ 
            title: result.message || '签到失败', 
            icon: 'error'
          })
        }
      } catch (error) {
        wx.hideLoading()
        wx.showToast({ 
          title: '网络错误，请重试', 
          icon: 'error'
        })
        console.error('签到失败:', error)
      }
    },

    // 刷新数据
    onPullDownRefresh() {
      wx.showLoading({ title: '刷新中...' })
      
      // 模拟网络请求
      setTimeout(() => {
        this.initCalendar()
        wx.hideLoading()
        wx.stopPullDownRefresh()
        wx.showToast({ title: '刷新成功', icon: 'success' })
      }, 1000)
    }
  }
})